package com.telsoft.hms.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SqlUtil {
	// public static long getSequenceValue(Connection mConnection,
	// String sequenceName) throws SQLException {
	// long result = 0;
	// PreparedStatement mStmt = null;
	// ResultSet mRs = null;
	// try {
	// StringBuilder sb = new StringBuilder();
	// sb.append("SELECT ").append(sequenceName).append(".NEXTVAL")
	// .append(" FROM DUAL");
	// mStmt = mConnection.prepareStatement(sb.toString());
	// mRs = mStmt.executeQuery();
	// if (mRs.next()) {
	// result = mRs.getLong("NEXTVAL");
	// }
	// } finally {
	// if (mRs != null) {
	// mRs.close();
	// }
	// if (mStmt != null) {
	// mStmt.close();
	// }
	// }
	// return result;
	// }

	public static String getSequenceValue(Connection cn, String sequenceName)
			throws Exception {
		return getSequenceValue(cn, sequenceName, true);
	}

	public static String getSequenceValue(Connection cn, String sequenceName,
			boolean bAutoCreate) throws Exception {
		// SQL command to sequence value
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT ").append(sequenceName).append(".NEXTVAL FROM DUAL ");
		// Get query data
		try {
			PreparedStatement stmt = cn.prepareStatement(sb.toString());
			ResultSet rs = stmt.executeQuery();
			rs.next();
			String strReturn = rs.getString(1);
			rs.close();
			stmt.close();
			return strReturn;

		} catch (Exception ex) {
			if (ex.getMessage() != null
					&& ex.getMessage().startsWith("ORA-02289")) {
				if (!bAutoCreate) {
					throw ex;

				} else {
					StringBuilder strSeq = new StringBuilder();
					sb.append("CREATE SEQUENCE ").append(sequenceName)
							.append(" START WITH 50");
					PreparedStatement stmt = cn.prepareStatement(strSeq
							.toString());
					stmt.execute();
					stmt.close();
					return "50";
				}

			} else {
				throw ex;
			}
		}
	}
}
